<template>
<!--    使用antv/g6在canvas中先画一张图片，然后在图片中在圈出相应标签，标签旁并标注相应得文本，标签能动态勾选显示隐藏，颜色变化，圈线和文本根据标签得变化而变化-->
    <div class="canvas-tem">
        <a-row>
            <a-col :span="3">
                <a-checkbox-group @change="onChange" :defaultValue="checkBoxs">
                    <div class="unit-information-tem">
                        <color-picker v-model="colors[0]" type="sketch" @change="onChangeColor"/>
                        <a-checkbox value="0" @change="checkBoxChange">
                            <span title="item.text">真标签</span>
                        </a-checkbox>
                    </div>
                    <div class="unit-information-tem" v-for="(item,index) in unitInformation" :key="index">
                        <color-picker v-model="colors[item.submitId]" type="sketch" @change="onChangeColor"/>
                        <a-checkbox :value="item.submitId" @change="checkBoxChange">
                            <span :title="item.companyName">{{item.companyName}}</span>
                        </a-checkbox>
                    </div>
                </a-checkbox-group>
            </a-col>
            <a-col :span="21" id="canvasWrapTem">
                <div id="canvas"></div>
            </a-col>
        </a-row>
    </div>
</template>

<script>
    //自定义组件
    G6.registerNode('power-ai', {
        draw(cfg, group) {
            if (!cfg.isUpdate) {
                // 如果 cfg 中定义了 style 需要同这里的属性进行融合
                const shape = group.addShape('image', {
                    attrs: {
                        x: cfg.x,
                        y: cfg.y,
                        img: cfg.img,
                        width: cfg.size[0],
                        height: cfg.size[1]
                    }
                });

                for (let key in cfg.children) {
                    const node = cfg.children[key];
                    group.addShape('rect', {
                        attrs: {
                            x: node.x,
                            y: node.y,
                            width: node.size[0],
                            height: node.size[1],
                            stroke: node.stroke,
                            lineWidth: node.lineWidth
                        }
                    });
                    group.addShape('text', {
                        attrs: {
                            x: node.x, // 居中
                            y: node.y - 5,
                            textBaseline: 'middle',
                            text: node.label,
                            fill: node.stroke
                        }
                    });
                }
                return shape;
            }
        },
        update(cfg, node){
            const group = node.getContainer(); // 获取容器
            const children1 = group.findAll(function (item) {
                return item.get('type') == 'rect';       // 获取所有type等于rect的元素
            });
            //先清空
            children1.map(item => {
                group.removeChild(item)
            })
            const children2 = group.findAll(function (item) {
                return item.get('type') == 'text';       // 获取所有type等于text的元素
            });
            children2.map(item => {
                group.removeChild(item)
            })
            //再追加画
            if (cfg.children.length > 0) {
                for (let key in cfg.children) {
                    const node = cfg.children[key];
                    group.addShape('rect', {
                        attrs: {
                            x: node.x,
                            y: node.y,
                            width: node.size[0],
                            height: node.size[1],
                            stroke: node.stroke,
                            lineWidth: node.lineWidth
                        }
                    });
                    group.addShape('text', {
                        attrs: {
                            x: node.x, // 居中
                            y: node.y - 5,
                            textBaseline: 'middle',
                            text: node.label,
                            fill: node.stroke
                        }
                    });
                }
            }
        }
    });
    import tu from '../assets/img/tu.jpg'
    import G6 from '@antv/g6'
    import {VueColorpicker} from 'vue-pop-colorpicker'
    export default {
        name: "antvG6",
        components: {'color-picker': VueColorpicker},
        data() {
            return {
                colordb: ["rgb(245, 166, 35)", "rgb(248, 231, 28)", "rgb(139, 87, 42)", "rgb(126, 211, 33)", "rgb(65, 117, 5)", "rgb(189, 16, 224)", "rgb(144, 19, 254)"],
                colors: {
                    '0': "rgb(208, 2, 27)"
                },
                unitInformation: [
                    {
                        submitId: "1201735944516931586",
                        companyName: "北京百度4444"
                    }, {
                        submitId: "1201706080694964226",
                        companyName: "北京成都成都成都"
                    }
                ],
                tagsParams: {
                    // dutiesId: this.unitInformation[0].dutiesId,
                    submitIds: [],
                    filename: ""
                },
                tagsData: {
                    "0": [{
                        "submitId": "0",
                        "cls": "hand",
                        "xc": 0.781616,
                        "yc": 0.79204,
                        "w": 0.079581,
                        "h": 0.105805
                    }, {
                        "submitId": "0",
                        "cls": "hand",
                        "xc": 0.458258,
                        "yc": 0.482815,
                        "w": 0.048888,
                        "h": 0.077585
                    }],
                    "1201735944516931586":[{
                        "submitId":"1201735944516931586",
                        "cls":"hand",
                        "xc":0.781616,
                        "yc":0.79204,
                        "w":0.079581,
                        "h":0.105805
                    },{
                        "submitId":"1201735944516931586",
                        "cls":"hand",
                        "xc":0.458258,
                        "yc":0.482815,
                        "w":0.048888,
                        "h":0.077585
                    }],
                    "1201706080694964226":[{
                        "submitId":"1201706080694964226",
                        "cls":"hand",
                        "xc":0.781616,
                        "yc":0.79204,
                        "w":0.079581,
                        "h":0.105805
                    },{
                        "submitId":"1201706080694964226",
                        "cls":"hand",
                        "xc":0.458258,
                        "yc":0.482815,
                        "w":0.048888,
                        "h":0.077585
                    }]
                },
                drawTagsData: {},
                isUpdate: false,
                graph: null,
                image: null,
            }
        },
        computed: {
            checkBoxs() {//默认选中标签
                let result = ['0']
                this.unitInformation.forEach(item => {
                    result.push(item.submitId)
                })
                return result
            }
        },
        mounted() {
            //初始化画布
            this.initCanvas()
            this.tagsParams.submitIds = this.checkBoxs
            this.computedColor()
            this.drawImage(this.tagsParams, this.tagsData)
        },
        methods: {
            initCanvas(){
                let warp = document.getElementById("canvasWrapTem");
                this.graph = new G6.Graph({
                    container: 'canvas',  // String | HTMLElement，必须，在 Step 1 中创建的容器 id 或容器本身
                    width: warp.offsetWidth,              // Number，必须，图的宽度
                    height: warp.offsetHeight,              // Number，必须，图的高度
                    modes: {
                        default: ['drag-node', 'zoom-canvas']
                    },
                    fitView: true
                });
            },
            computedColor() {
                this.unitInformation.forEach((item, index) => {
                    this.colors[item.submitId] = this.colordb[index + 1]
                })
            },
            onChange(checkedValues) {
                this.tagsParams.submitIds = checkedValues
            },
            checkBoxChange(e) {
                const key = e.target.value
                const checked = e.target.checked;
                const tags = this.tagsData[key];
                this.isUpdate = true

                if(checked) {
                    this.drawTagsData[key] = tags
                } else {
                    if(Object.keys(this.drawTagsData).length === 0) {
                        Object.assign(this.drawTagsData,this.tagsData)
                    }
                    delete this.drawTagsData[key]
                }
                this.drawImage(this.tagsParams, this.drawTagsData)
            },
            onChangeColor() {
                this.isUpdate = true
                if(Object.keys(this.drawTagsData).length === 0) {
                    Object.assign(this.drawTagsData,this.tagsData)
                }
                this.drawImage(this.tagsParams, this.drawTagsData)
            },
            drawImage(params,data) {
                this.image = new Image()
                //调接口动态获取图片
                this.image.src = tu
                // 判断是否有缓存
                if (this.image.complete) {
                    this.drawRectangle(data)
                } else {
                    const that = this
                    // 加载完成执行
                    this.image.onload = function () {
                        that.delayFun(data)
                    }
                }
            },
            delayFun(data) {
                const that = this
                if (!(this.image.complete)) {
                    setTimeout(() => {
                        that.delayFun(data)
                    }, 300)
                } else {
                    this.drawRectangle(data)
                }
            },
            drawRectangle(data) {
                if (!this.isUpdate) {
                    let data2 = {
                        nodes: [
                            {
                                id: 'image',
                                img: this.image,
                                shape: 'power-ai',
                                x: 0,
                                y: 0,
                                size: [this.image.width, this.image.height],
                                children: []
                            }
                        ]
                    }
                    for (let key in data) {
                        const item = data[key]
                        item.forEach(node => {
                            const x = (node.xc - node.w / 2) * this.image.width
                            const y = (node.yc - node.h / 2) * this.image.height
                            data2.nodes[0].children.push({
                                id: node.id,
                                x: x,
                                y: y,
                                label: node.cls,
                                size: [node.w * this.image.width, node.h * this.image.height],
                                stroke: this.colors[key],
                                lineWidth: 2,
                            })
                        })
                    }
                    this.graph.data(data2);  // 读取 Step 2 中的数据源到图上
                    this.graph.render();    // 渲染图
                } else {
                    const model = {
                        id: 'image',
                        shape: 'power-ai',
                        children: [],
                        isUpdate: this.isUpdate
                    }
                    for (let key in data) {
                        const item = data[key]
                        item.forEach(node => {
                            const x = (node.xc - node.w / 2) * this.image.width
                            const y = (node.yc - node.h / 2) * this.image.height
                            model.children.push({
                                id: node.id,
                                x: x,
                                y: y,
                                label: node.cls,
                                size: [node.w * this.image.width, node.h * this.image.height],
                                stroke: this.colors[key],
                                lineWidth: 2,
                            })
                        })
                    }
                    this.graph.findById('image').update(model)
                    this.graph.refresh()
                    this.isUpdate = false
                }
            },
        }
    }
</script>

<style lang="scss">
div.canvas-tem{
    .ant-row,
    .ant-col-3,
    .ant-col-21 {
        height: 100%;
    }
    .ant-col-3{
        border-right: 1px solid #eaeaea;
    }
    .ant-checkbox-group {
        width: 100%;
        padding: 15px 0 0 20px;
        div.unit-information-tem{
            text-align: left;
            padding: 5px 0;
            color: #333333;
            position: relative;
            div.vue-colorpicker {
                display: inline-block;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
                height: 17px;
                padding: 0;
                border: none;
                border-radius: 4px;
                font-size: 0;
                cursor: pointer;
                span.vue-colorpicker-btn {
                    border: 1px solid #c2c9c9;
                    height: 17px;
                    width: 17px;
                }
            }
            .ant-checkbox-wrapper {
                position: absolute;
                top: 2px;
                margin-left: 8px;
            }
        }
    }
    #canvas{
        width: 100%;height: 100%
    }
}
</style>
